package com.gz.steak.utils.jwt;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @Author 刘牌
 * @Date 2020/3/13 0013 8:39
 * @Version 1.0
 */

public class AESUtil {
    private final static Logger logger = LoggerFactory.getLogger(AESUtil.class);

    public static String parseByte2HexStr(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0 ; i < bytes.length ; i++){
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1){
                hex = '0' + hex;
            }
            stringBuffer.append(hex.toUpperCase());
        }
        return stringBuffer.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static byte[] decrypt(byte[] data , String key){
        if (data != null){
            try {
                KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(key.getBytes());
                keyGenerator.init(128,random);
                SecretKey secretKey = keyGenerator.generateKey();
                byte[] codeFormat = secretKey.getEncoded();
                SecretKeySpec secretKeySpec = new SecretKeySpec(codeFormat,"AES");
                Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
                byte[] result = cipher.doFinal(data);
                return result;
            }catch (Exception e){
                logger.info("加密出错 "+e);
            }
        }
        return null;
    }

    public static byte[] encrypt(String data, String key) {
        if(data != null){
            try {
                KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
                //选择一种固定算法，为了避免不同java实现的不同算法，生成不同的密钥，而导致解密失败
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(key.getBytes());
                keyGenerator.init(128, random);
                SecretKey secretKey = keyGenerator.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                byte[] byteContent = data.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
                byte[] result = cipher.doFinal(byteContent);
                return result; // 加密
            } catch (Exception e) {
                logger.info("出错 "+e);
            }
        }
        return null;
    }


    public static String encryptToString(String data, String key){
        if (data == null){
            return null;
        }
        else {
            return parseByte2HexStr(encrypt(data,key));
        }
    }

    public static String decryToString(String encryptData , String key){
        if (encryptData == null){
            return null;
        }
        else {
            return  new String(decrypt(parseHexStr2Byte(encryptData), key));
        }
       // return StringUtils.isEmpty(encryptData)?new String(decrypt(parseHexStr2Byte(encryptData),key)):null;
    }
}
